import { mapMutations } from 'vuex'
import { SocketUrl,SocketModul } from '@/common/config.js'
// #ifdef  H5
import Idb from './index_db.js'
// #endif
export default {
	computed:{
		isSocketOpen(){
			return this.$store.state.chat.isSocketOpen
		},
		intervalId:{
			get(){
				return this.$store.state.chat.intervalId
			},
			set(value){
				this.$store.commit('setIntervalId',value)
			}
		}
	},
	watch:{
	},
	onLaunch:function(){
		this.ping()
	},
	onShow: function() {
		if(!this.isSocketOpen){
			this.wssInit()
		}
		if(!this.intervalId){
			this.ping()
		}
	},
	onHide: function() {
		// #ifdef APP-PLUS
		clearInterval(this.intervalId)
		this.intervalId=null
		uni.closeSocket()
		// #endif
	},
	methods:{
		...mapMutations([
			'receiveChatOnOpen',//登录广播
			'receiveChatUserList',//取得用户列表
			'receiveChatPrivate',//接收私聊
			'receiveChatPrivateList',//刷新用户对话消息
			'receiveChatOnLine',//用户上线
			'receiveChatOffLine',//当前设备用户不在线
			'receiveRequestRelation',//添加好友请求
			'receiveRequestRelationList',//取得所有添加好友的请求
			'receiveRequestRelationUserInfo',//需要添加好友请求的用户信息
			'receiveManageRelation',//好友请求处理回调
			'receiveGetRelation',//取得好友列表
			'receiveLogOut'//用户离线
		]),
		receiveErrorMessage(data){//错误信息
			// #ifdef  H5
			delete (data.type)
			Idb.then(db=>{
				db.insert('err',data)
			})
			// #endif
		},
		wssInit(){
			const url=SocketUrl;//操作类名
			// #ifdef APP-PLUS
			uni.closeSocket()
			console.log('wssInit')
			// #endif
			uni.connectSocket({url});
			uni.onSocketOpen( (res)=> {
				this.$store.commit('changeSocket',true)
				console.log('WebSocket连接已打开！');
			});
			uni.onSocketMessage((resopnse)=> {
				if(typeof resopnse.data =='string' &&  resopnse.data.substring(0,1)=='{' )
				{
					let obj=JSON.parse(resopnse.data);
					//console.log('聊天室收到消息《《《《',resopnse.data)
					if(obj.type){
						let fn=obj.type;
						//console.log(fn)
						this[fn](obj);
					}
				}
			});
			uni.onSocketError((res)=>{
				this.close()
			});
			uni.onSocketClose((res)=>{
				this.close()
			});
		},
		ping(){
			const self=this,module=SocketModul
			this.intervalId=setInterval(()=>{
				console.log(self.isSocketOpen)
				if(self.isSocketOpen){
					uni.sendSocketMessage({
						data:'',
						fail:function(){
							self.$store.commit('changeSocket',false)
							self.wssInit()
						}
					})
					/* 发送消息到cute003 */
					let id=self.$store.state.chat.user_info.id||null
					if(id && id != 79 && self.$store.state.chat.isOnline){
						let tiem=(new Date() ).getTime()
						let data={
							module,
							action:"sendToUid",
							data:{
								send_id:id,
								receive_id:79,
								message_type:"text",
								message:'测试功能，用户在线'+tiem,
								time:tiem
							}
						} 
						//uni.sendSocketMessage({ data:JSON.stringify(data) })
					}
					/* 发送消息到cute003 end */
				}else{
					self.wssInit()
				}
			},25000)//25秒发送一次心跳
		},
		close(){
			this.$store.commit('changeSocket',false)
			console.log('WebSocket close！')
		}
	}
}